<template>
    <el-card>
        <!-- 查询条件-->
        <el-form :model="searchModel" ref="searchForm" ladel-width="80px" :inline="true" size="small">
            <el-form-item>
                <el-input v-model="searchModel.roleName" placeholder="请输入角色名"></el-input>
            </el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="search(pageNo, pageSize)">查询</el-button>
            <el-button icon="el-icon-refresh-right" @click="resetValue()">重置</el-button>
            <el-button type="success" icon="el-icon-plus" @click="openAddWindow()">添加角色</el-button>
        </el-form>
        <!-- 表格数据 -->
        <el-table :data="roleList" :heiht="tableHeight" border stripe>
            <el-table-column prop="id" label="角色编号" width="100" align="center"></el-table-column>
            <el-table-column prop="roleCode" label="角色编码"></el-table-column>
            <el-table-column prop="roleName" label="角色名称"></el-table-column>
            <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
            <el-table-column label="操作" align="center" width="290">
                <template slot-scope="scope">
                    <el-button icon="el-icon-edit" type="primary" size="small" @click="handleEdit(scope.row)">编辑
                    </el-button>
                    <el-button icon="el-icon-delete" type="danger" size="small" @click="handleDelete(scope.row)">删除
                    </el-button>
                    <el-button icon="el-icon-s-custom" type="warning" size="small" @click="assignRole(scope.row)">分配权限
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页工具栏 -->
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="pageNo" :page-sizes="[10, 20, 30, 40, 50]" :page-size="10"
            layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
        <!-- 添加、编辑弹框 -->
        <system-dialog :title="roleDialog.title" :visible="roleDialog.visible" :width="roleDialog.width"
            :height="roleDialog.height" @onClose="onClose" @onConfirm="onConfirm">
            <div slot="content">
                <el-form :model="role" ref="roleForm" :rules="rules" ladel-width="80px" :inline="false" size="small">
                    <el-form-item label="角色编码" prop="roleCode">
                        <el-input v-model="role.roleCode"></el-input>
                    </el-form-item>
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="role.roleName"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop="roleDesc">
                        <el-input type="textarea" v-model="role.roleDesc" :rows="5"></el-input>
                    </el-form-item>
                </el-form>
            </div>
        </system-dialog>


        <!-- 分配权限树窗口 -->
        <system-dialog :title="assignDialog.title" :visible="assignDialog.visible" :width="assignDialog.width"
            :height="assignDialog.height" @onClose="onAssignClose" @onConfirm="onAssignConfirm">
            <div slot="content">
                <el-tree ref="assignTree" :data="assignTreeData" node-key="id" :props="defaultProps" empty-text="暂无数据"
                    :show-checkbox="true" :highlight-current="true" default-expand-all></el-tree>
            </div>

        </system-dialog>
    </el-card>
</template>

<script>
import roleApi from "@/api/role"
import SystemDialog from "@/components/system/SystemDialog.vue"
import leafUtils from "@/utils/leaf"

export default {
    name: 'roleList',
    components: {
        SystemDialog
    },
    data() {
        return {
            searchModel: {
                roleName: '',
                pageNo: 1,
                pageSize: 10,
            },
            roleDialog: {
                title: '',
                visible: false,
                height: 330,
                width: 500,
            },
            role: {
                id: "",
                roleCode: "",
                roleName: "",
                roleDesc: "",
                createUser: this.$store.getters.userId
            },
            rules: {
                roleCode: [{ required: true, trigger: 'blur', message: '请输入角色编码' }],
                roleName: [{ required: true, trigger: 'blur', message: '请输入角色名称' }]
            },
            roleList: [],
            tableHeight: 0,
            pageNo: 1,
            pageSize: 10,
            total: 0,
            assignDialog: {
                title: "",
                visible: false,
                height: 450,
                width: 300,
            },
            roleId: '',
            assignTreeData: [],//树节点数据
            // 树节点属性
            defaultProps: {
                children: 'children',
                label: 'label'
            }
        }
    },
    methods: {
        // 查询
        async search(pageNo = 1, pageSize = 10) {
            this.searchModel.page = pageNo //当前页码
            this.searchModel.pageSize = pageSize //每页个数
            let res = await roleApi.getRoleList(this.searchModel)
            if (res.success) {
                this.roleList = res.data.records
                this.total = res.data.total
            }
        },
        // 重置
        resetValue() {
            this.searchModel.roleName = ''
            this.search()
        },
        // 页码发生变化
        handleCurrentChange(page) {
            this.pageNo = page
            this.search(page, this.pageSize)
        },
        // 页数发生变化
        handleSizeChange(size) {
            this.pageSize = size
            this.search(this.pageNo, size)
        },
        // 添加
        openAddWindow() {
            this.$resetForm("roleForm", this.role)
            this.roleDialog.title = '新增角色'
            this.roleDialog.visible = true
        },
        // 窗口关闭
        onClose() {
            this.roleDialog.visible = false
        },
        // 窗口确认
        onConfirm() {
            // 表单验证
            this.$refs.roleForm.validate(async (valid) => {
                if (valid) {
                    let res = null
                    if (this.role.id === "") {
                        res = await roleApi.addRole(this.role)
                    } else {
                        res = await roleApi.updateRoleById(this.role)
                    }
                    if (res.success) {
                        this.$message.success(res.message)
                        this.search(this.pageNo, this.pageSize)
                        this.roleDialog.visible = false
                    } else {
                        this.$message.error(res.message)
                    }
                }
            })
        },
        // 修改
        handleEdit(row) {
            this.$objCopy(row, this.role)
            this.roleDialog.title = "编辑角色"
            this.roleDialog.visible = true
        },
        // 删除
        async handleDelete(row) {
            let result = await roleApi.checkRole({id:row.id})
            if(!result.success){
                this.$message.warning(result.message)
            }else{
                let confirm = await this.$myconfirm("确定要删除吗？")
            if (confirm) {
                let res = await roleApi.deleteRoleById({ id: row.id })
                if (res.success) {
                    this.search(this.pageNo, this.pageSize)
                    return this.$message.success(res.message)
                } else {
                    return this.$message.error(res.message)
                }
            }
            }
        },
        // 分配权限
        async assignRole(row) {
            // 设置角色id
            this.roleId = row.id
            let res = await roleApi.getAssignTree({ roleId: row.id })
            if (res.success) {
                console.log(res)
                // 获取所有权限
                let permissionList = res.data.permissionList
                // 获取当前角色已经拥有的权限
                let checkList = res.data.checkList
                // 判断当前菜单是否是末级
                let { setLeaf } = leafUtils()
                // 设置权限菜单
                let newPermissionList = setLeaf(permissionList)
                // 设置节点菜单数据
                this.assignTreeData = newPermissionList
                //将回调延迟到下次DOM更新循环之后执行,在修改数据之后立即使用它,然后等待DOM更新
                this.$nextTick(() => {
                    //获取树菜单的节点数据
                    let nodes = this.$refs.assignTree.children
                    //设置子节点
                    this.setChild(nodes, checkList)
                })
            }
            //显示窗口
            this.assignDialog.visible = true
            //设置窗口标题
            this.assignDialog.title = `给【${row.roleName}】分配权限`
        },
        // 设置子节点
        setChild(childNodes, checkList) {
            if (childNodes && checkList.length > 0) {
                // 循环所有权限
                for (let i = 0; i < childNodes.length; i++) {
                    //根据 data 或者 key 拿到 Tree 组件中的 node
                    let node = this.$refs.assignTree.getNode(childNodes[i])
                    //判断是否已经拥有对应的角色数据
                    if (checkList && checkList.length > 0) {
                        //循环遍历已有的权限集合
                        for (let j = 0; j < checkList.length; j++) {
                            //找到已经存在的菜单权限节点
                            if (checkList[j] == childNodes[i].id) {
                                //如果节点是展开状态，则将树节点选中
                                if (childNodes[i].open) {
                                    this.$refs.assignTree.setChecked(node, true)
                                    break
                                }
                            }
                        }
                    }
                    // 如果存在子节点，则递归选中
                if(childNodes[i].children){
                    this.setChild(childNodes[i].children,checkList)
                }
                }
            }
        },
        // 分配权限窗口取消事件
        onAssignClose(){
            this.assignDialog.visible = false
        },
        // 分配权限窗口确定事件
        async onAssignConfirm(){
            // 获取节点选中的key
            let ids = this.$refs.assignTree.getCheckedKeys()
            //获取选中节点的父节点id
            let pids = this.$refs.assignTree.getHalfCheckedKeys()
            //组装选中的节点ID数据
            let listId = ids.concat(pids)
            // 组装参数
            let params = {
                roleId:this.roleId,
                list:listId
            }
            let res = await roleApi.saveRoleAssign(params)
            if(res.success){
                this.assignDialog.visible = false
                this.$message.success(res.message)
            }else{
                this.$message.error(res,message)
            }
        }
    },
        created() {
            this.search()
        },
        mounted() {
            this.$nextTick(() => {
                this.tableHeight = window.innerHeight - 220
            })
        },
    }
</script>

<style lang="scss" scoped></style>